package com.meshnetics.gb.type.impl.custom;

import com.meshnetics.gb.type.impl.ByteUtils;
import com.meshnetics.gb.type.impl.zcl.EnumElement;

/**
 * Element of finite enumeration. Unique by its code and have additional string label attached to code. Automatically
 * registers intself in finite enumeration type passed to constructor.
 *
 * @author AKovylin
 */
public abstract class FiniteEnumerationElement extends EnumElement {
    private final String name;

    protected FiniteEnumerationElement(FiniteEnumeration type, long value, String name) {
        this(type, codeFromLong(value, type), name);
    }

    private static byte[] codeFromLong(long code, FiniteEnumeration type) {
        byte[] bCode = new byte[type.getByteSize()];
        ByteUtils.fillFromLong(code, bCode, 0, bCode.length);
        return bCode;
    }

    FiniteEnumerationElement(FiniteEnumeration type, byte[] value, String name) {
        super(type, value);
        if (name == null) {
            throw new NullPointerException("name is null");
        }
        this.name = name;
        type.registerValue(this);
    }

    public String getName() {
        return name;
    }

    byte[] getInnerBytesUnsafe() {
        return value;
    }

    public boolean equals(Object obj) {
        return super.equals(obj) && this.name.equals(((FiniteEnumerationElement) obj).name);
    }
}
